package com.jeaven.classfile.classreader;

import com.jeaven.classfile.constantpool.ConstantPool;
import com.jeaven.instruction.*;

import java.io.DataInputStream;
import java.io.IOException;


public abstract class InstructionReader {
    // 根据 code 属性的第一个字节来解析不同的指令并返回
    // 具体的字节码的操作数可以参见下面的文章
    // https://blog.csdn.net/weixin_40234548/article/details/81533673
    public static Instruction read(int opCode, DataInputStream is, ConstantPool constantPool)
            throws IOException {
        switch (opCode) {
            case 0x0:
                return new NopInst();
            case 0x04:
                return new iconst1Inst();
            case 0x84:
                return new iincInst(is.readUnsignedByte(), is.readByte());
            case 0xb2:
                int gsindex = is.readUnsignedShort();
                return new getstaticInst();
            case 0xb6:
                int ivIndex = is.readUnsignedShort();
                // todo
//                return new invokevirtualInst(
//                        Utils.getClassNameByMethodDefIdx(constantPool, ivIndex),
//                        Utils.getMethodNameByIMethodDefIdx(constantPool, ivIndex),
//                        Utils.getMethodTypeByMethodDefIdx(constantPool, ivIndex)
//                );
                return new invokevirtualInst();
            case 0xb1:
                return new returnInst();
            case 0x3c:
                return new istore1Inst();
            case 0x1b:
                return new iload1Inst();
            default:
                return new TestInst();
        }
    }
}